import $store from '@/store/index.js';
export default {
	common:{
		method: 'GET',
		header:{
			"Content-Type":"application/x-www-form-urlencoded"
		},
		data:{}
	},
	request(options = {}){
		if(options.url.indexOf('http') == -1) options.url = $store.state.host + options.url;
		options.method = options.method || this.common.method;
		options.header = options.header || this.common.header;
		if(uni.getStorageSync('login_atk')) options.header['token'] = uni.getStorageSync('login_atk');
		// console.log(options.url +'运行入参=>' + JSON.stringify(options.data));//打印
		return new Promise((reslove,reject)=>{
			if (options.showLoading) uni.showLoading({
				title: options.loadingTitle || '加载中...',
				mask: true
			});
			uni.request({
				...options,
				success: (result) => {
					var data = result.data || {};
					if (result.statusCode !== 200) {
						console.log(options.url +'服务器错误=>'+result.statusCode);
						if(result.statusCode == 401){
							uni.navigateTo({url:'/pages/login/login'});
							$store.commit('logout');
						}else{
							uni.showToast({title: '服务器错误，请稍后再试！',icon: 'none',})
						}
						return reject(data);
					}
					if(data.code == 401){
						uni.navigateTo({url:'/pages/login/login'});
						$store.commit('logout');
						return reject(data);
					}
					if(options.log){
						// console.log(options.url +'运行成功=>'+JSON.stringify(result.data));//打印
					} 
					if(options.showLoading) uni.hideLoading();
					return reslove(data);
				},
				fail:(err)=>{
					console.log(options.url + '运行失败->' + JSON.stringify(err));
					if(options.showLoading) uni.hideLoading();
					uni.showToast({title: '网络请求失败，请稍后再试！',icon: 'none',})
					return reject(err);
				}
			});
		})
	},
	get(url,data={},options = {}){
		options.url = url;
		options.data = data;
		options.method = 'GET';
		return this.request(options)
	},	
	post(url,data={},options = {}){
		options.url = url;
		options.data = data;
		options.method = 'POST';
		options.header['content-type'] = 'application/json';
		return this.request(options)
	},
	
	upload(url, options = {}) {
		options.url = $store.state.host + url;
		options.header = options.header || {};
		if (uni.getStorageSync('login_atk')) options.header['token'] = uni.getStorageSync('login_atk');
		return new Promise((res, rej) => {
			uni.uploadFile({
				...options,
				success: (result) => {
					if (result.statusCode !== 200) {
						uni.showToast({
							title: '上传图片失败',
							icon: 'none'
						});
						rej(result)
					}
					let data = JSON.parse(result.data)
					if (typeof data == 'string') {
						data = JSON.parse(data);
					}
					res(data)
				},
				fail: (err) => {
					rej(err)
				}
			});
		})
	}
}